<template>
    <view class="chat-container">
        <block v-for="(item, index) in typeList" :key="index">
            <ant-notice :type="item" style="margin-bottom: 8px" :enableMarquee="true" onTap="handleTapLink" mode="link">每天可免费提问10次,次日0时更新</ant-notice>
        </block>
        <scroll-view class="chat-box" :scroll-y="true" :scroll-into-view="scrollToView">
            <view :class="'chat-message ' + item.type" :id="item.id" v-for="(item, index) in chatMessages" :key="index">
                <view class="message-content">
                    <image class="avatar" :src="item.avatar" mode="aspectFit" />
                    <view class="bubble">
                        {{ item.content }}
                    </view>
                </view>
            </view>
        </scroll-view>

        <form onSubmit="onSubmit" class="input-box">
            <input :value="message" name="message" onInput="onMessageInput" placeholder="你的山水管家顾问" class="box1" required />
            <button onTap="onSubmit" class="send-button">发送</button>
        </form>
    </view>
</template>

<script>

	import {
		ref,
		onMounted
	} from 'vue';
	import {
		onShow,
		onLoad
	} from '@dcloudio/uni-app';
	import {
		onPullDownRefresh,
		onReachBottom
	} from "@dcloudio/uni-app";

export default {
    components: {

    },
    data() {
        return {
            message: '',
            chatMessages: [],
            typeList: ['primary'],
            scrollToView: '' // 用于 scroll-into-view 的 id
        };
    },
    onLoad() {
        // 在页面加载时，添加AI机器人的初始消息
        let botAvatar = 'https://bpic.588ku.com/element_origin_min_pic/19/04/27/578456f43714d36fffc68ecc6f8c46e5.jpg'; // 机器人头像URL
        let initialMessage = {
            type: 'bot',
            content: '请问有什么可以帮到您？',
            avatar: botAvatar,
            id: `msg-${Date.now()}`
        };
        this.setData({
            chatMessages: [initialMessage],
            scrollToView: initialMessage.id // 初始化滚动到初始消息
        });
    },
    methods: {
        onMessageInput(e) {
            this.setData({
                message: e.detail.value
            });
        },

        onSubmit(e) {
            let that = this;
            let currentMessage = this.message;
            let userAvatar = 'https://tse3-mm.cn.bing.net/th/id/OIP-C.7FAY6Oj6V71QZbgvc9y45wHaHa?rs=1&pid=ImgDetMain'; // 用户头像URL
            let botAvatar = 'https://bpic.588ku.com/element_origin_min_pic/19/04/27/578456f43714d36fffc68ecc6f8c46e5.jpg'; // 机器人头像URL

            // 添加用户消息到 chatMessages
            let userMessage = {
                type: 'user',
                content: currentMessage,
                avatar: userAvatar,
                id: `user-${Date.now()}`
            };
            this.setData({
                chatMessages: [...this.chatMessages, userMessage],
                message: '',
                scrollToView: userMessage.id // 滚动到用户消息
            });

            // 添加“加载中”消息
            let loadingMessage = {
                type: 'bot',
                content: '加载中...',
                avatar: botAvatar,
                id: `loading-${Date.now()}`
            };
            this.setData({
                chatMessages: [...this.chatMessages, loadingMessage]
            });

            // 模拟API请求获取机器人回复
            uni.getStorage({
                key: 'openId',
                success: (res) => {
                    uni.request({
                        url: 'http://localhost:5657/chat',
                        method: 'POST',
                        data: {
                            openId: res.data.openId,
                            requestBody: currentMessage
                        },
                        headers: {
                            'content-type': 'application/json'
                        },
                        success: function (res) {
                            let count = res.data.count; // 假设后端返回的 count 字段
                            let responseMessage =
                                count >= 10
                                    ? {
                                          type: 'bot',
                                          content: '免费次数已用完',
                                          avatar: botAvatar,
                                          id: `response-${Date.now()}`
                                      }
                                    : {
                                          type: 'bot',
                                          content: res.data.data,
                                          avatar: botAvatar,
                                          id: `response-${Date.now()}`
                                      };

                            // 替换“加载中”消息为机器人回复
                            that.setData({
                                chatMessages: that.chatMessages.map((msg) => (msg.id === loadingMessage.id ? responseMessage : msg)),
                                scrollToView: responseMessage.id // 滚动到最新回复
                            });
                        },
                        fail: function (error) {
                            console.error('fail: ', JSON.stringify(error));
                            // 如果请求失败，替换“加载中”消息为错误消息
                            that.setData({
                                chatMessages: that.chatMessages.map((msg) =>
                                    msg.id === loadingMessage.id
                                        ? {
                                              type: 'bot',
                                              content: '请求失败，请稍后再试',
                                              avatar: botAvatar,
                                              id: `response-${Date.now()}`
                                          }
                                        : msg
                                ),
                                scrollToView: `response-${Date.now()}` // 滚动到最新错误消息
                            });
                        }
                    });
                }
            });
        },

        handleTapLink() {
            uni.alert({
                title: '提示',
                // 可选，弹窗标题
                content: '别点了，再点也是10次',
                // 主要内容
                buttonText: '确定' // 可选，按钮文字
            });
        }
    }
};
</script>
<style>
.chat-message {
    display: flex;
    margin-bottom: 8px;
}

.message-content {
    display: flex;
    align-items: center;
}

.chat-message.user {
    justify-content: flex-end;
}

.chat-message.bot {
    justify-content: flex-start;
}

.chat-message.user .message-content {
    flex-direction: row-reverse; /* 头像和气泡反向排列 */
}

.avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    margin: 0 8px;
}

.bubble {
    max-width: 70%;
    padding: 8px;
    border-radius: 4px;
    background-color: #e0e0e0;
    word-wrap: break-word;
}

.chat-message.user .bubble {
    background-color: #1cbbb4;
    color: #fff;
}
.chat-container {
    display: flex;
    flex-direction: column;
    height: 100vh;
    justify-content: space-between;
}
.chat-box {
    flex: flex;
    height: 100%;
    padding: 16px;
    overflow-y: auto;
    background-color: #f9f9f9;
}
.input-box {
    display: flex;
    align-items: center; /* 垂直居中对齐 */
    padding: 16px;
    background-color: #fff;
    border-top: 1px solid #e0e0e0;
}

.box1 {
    flex: 1; /* 使输入框占据剩余空间 */
    height: 40px; /* 设置输入框的高度 */
    padding: 8px; /* 设置输入框内边距 */
    font-size: 16px; /* 设置字体大小 */
    border: 1px solid #ccc; /* 设置边框 */
    border-radius: 4px; /* 设置边框圆角 */
    box-sizing: border-box; /* 使内边距和边框包含在宽度和高度内 */
    margin-right: 10px; /* 设置输入框和按钮之间的间距 */
}

.send-button {
    display: flex; /* 使用 flexbox 布局 */
    justify-content: center; /* 水平居中对齐 */
    align-items: center; /* 垂直居中对齐 */
    background-color: #baccd9; /* 设置按钮背景色 */
    border: none; /* 去掉按钮边框 */
    padding: 10px 20px; /* 设置按钮内边距 */
    color: #fff; /* 设置按钮文字颜色 */
    border-radius: 4px; /* 设置按钮圆角 */
    cursor: pointer; /* 设置鼠标指针为手型 */
    font-size: 16px; /* 设置字体大小 */
}

</style>
